/**
 * <pre>
 * Copyright:		Copyright(C) 2011-2012, ketayao.com
 * Filename:		com.ketayao.ketacustom.controller.IndexController.java
 * Class:			IndexController
 * Date:			2012-8-2
 * Author:			<a href="mailto:ketayao@gmail.com">ketayao</a>
 * Version          1.1.0
 * Description:		
 *
 * </pre>
 **/

package com.ketayao.ketacustom.controller;

import com.ketayao.ketacustom.SecurityConstants;
import com.ketayao.ketacustom.entity.main.Module;
import com.ketayao.ketacustom.entity.main.Permission;
import com.ketayao.ketacustom.entity.main.User;
import com.ketayao.ketacustom.exception.ServiceException;
import com.ketayao.ketacustom.log.Log;
import com.ketayao.ketacustom.log.LogMessageObject;
import com.ketayao.ketacustom.log.impl.LogUitls;
import com.ketayao.ketacustom.service.ModuleService;
import com.ketayao.ketacustom.service.UserService;
import com.ketayao.ketacustom.util.dwz.AjaxObject;
import com.ketayao.ketacustom.util.dwz.Page;
import com.ketayao.ketacustom.util.persistence.DynamicSpecifications;
import fms.entity.ServiceStatus;
import fms.service.CptSendService;
import fms.service.ServiceStatusService;
import org.apache.shiro.authz.annotation.RequiresUser;
import org.apache.shiro.session.mgt.eis.SessionDAO;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author <a href="mailto:ketayao@gmail.com">ketayao</a>
 *         Version  1.1.0
 * @since 2012-8-2 下午5:45:57
 */
@Controller
@RequestMapping("")
public class IndexController {

    private static final Logger log = LoggerFactory.getLogger(IndexController.class);

    @Autowired
    private UserService userService;

    @Autowired
    private ModuleService moduleService;

    //	@Autowired
//	private OrganizationService organizationService;
    @Autowired
    private CptSendService cptSendService;

    @Autowired
    private ServiceStatusService serviceStatusService;


    @Autowired
    private SessionDAO sessionDAO;

    private static final String INDEX = "index";
    private static final String INDEX2 = "index2";
    private static final String UPDATE_PASSWORD = "management/index/updatePwd";
    private static final String UPDATE_BASE = "management/index/updateBase";
    // 用于确保本机只有一个用户登录
//	private static final String LOGIN_PAGE = "login";
//	private static final String REPEAT_LOGIN_MSG = "登录失败,已有用户在本机登录,请先退出后再登录!";
//	String username = "admin";
//	map.put("msg", msg);
//	map.put("username", username);
//	
//	return LOGIN_PAGE;

    // 用户身份验证后，获取其可以查看的模块，初始化页面
    @Log(message = "{0}登录了系统。")
    @RequiresUser
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index(ServletRequest request, Page page,
                        Map<String, Object> map) {
        Subject subject = org.apache.shiro.SecurityUtils.getSubject();
        User user = userService.getByUsername(subject.getPrincipal().toString());

//		// 获取可浏览的模块列表
//		Module menuModule = getMenuModule(SecurityUtils.getSubject());
        map.put(SecurityConstants.LOGIN_USER, user);
//		map.put("menuModule", menuModule);
//
//		LogUitls.putArgs(LogMessageObject.newWrite().setObjects(new Object[]{shiroUser.getLoginName()}));
//
//		// 在线用户功能
//		Collection<Session> sessions = null;
//		sessions = sessionDAO.getActiveSessions();
//		Iterator it = sessions.iterator();
//		Set<String> loginNames = new HashSet<String>();
//		while(it.hasNext()){
//			Session session = (Session) it.next();
//			if(session!=null){
//				if(session.getAttribute("org.apache.shiro.subject.support.DefaultSubjectContext_PRINCIPALS_SESSION_KEY") != null)
//					loginNames.add(session.getAttribute("org.apache.shiro.subject.support.DefaultSubjectContext_PRINCIPALS_SESSION_KEY").toString());
//			}
//		}
//		Iterator iteratornames = loginNames.iterator();
//		List<User> users = new ArrayList<User>();
//		while(iteratornames.hasNext()){
//			User loginUser = userService.getByUsername((String)iteratornames.next());
//
//			// 属于相同公司的用户才相互可见 or 当前用户是admin
//			if ( (loginUser.getOrganization().getId() == user.getOrganization().getId())
//				|| (user.getUsername().equals("admin")) ) {
//				users.add(loginUser);
//			}
//
//		}
//		map.put("users", users);
//
//		// 服务状态监控功能
        Specification<ServiceStatus> sp = DynamicSpecifications
                .bySearchFilter(request, ServiceStatus.class);
        List<ServiceStatus> serviceStatuss = serviceStatusService.findByExample(sp, page);
        map.put("serviceStatuss", serviceStatuss);

        return INDEX;
    }

    @ResponseBody
    @RequestMapping(value = "/serviceStatus/load", method = RequestMethod.GET)
    public Map loadServiceStatus(ServletRequest request) {
        Map<String, Object> map=new HashMap<>();
        List<ServiceStatus> serviceStatuss = serviceStatusService.findAll(new Page());
        map.put("serviceStatuss", serviceStatuss);

        return map;
    }

    private void check(Module module, Subject subject) {
        List<Module> list1 = new ArrayList<Module>();
        for (Module m1 : module.getChildren()) {
            // 只加入拥有show权限的Module
            if (subject.isPermitted(m1.getSn() + ":" + Permission.PERMISSION_SHOW)) {
                check(m1, subject);
                list1.add(m1);
            }
        }
        module.setChildren(list1);
    }

    // 返回修改密码页面
    @RequiresUser
    @RequestMapping(value = "/updatePwd", method = RequestMethod.GET)
    public String preUpdatePassword() {
        return UPDATE_PASSWORD;
    }

    //执行密码修改操作
    @Log(message = "{0}修改了密码。")
    @RequiresUser
    @RequestMapping(value = "/updatePwd", method = RequestMethod.POST)
    public String updatePassword(ServletRequest request, String plainPassword,
                          String newPassword, String rPassword) {
        Subject subject = org.apache.shiro.SecurityUtils.getSubject();
        User user = userService.getByUsername(subject.getPrincipal().toString());
        //User user = SecurityUtils.getLoginUser();

        if (newPassword != null && newPassword.equals(rPassword)) {
            user.setPlainPassword(plainPassword);
            try {
                userService.updatePwd(user, newPassword);
            } catch (ServiceException e) {
                LogUitls.putArgs(LogMessageObject.newIgnore());//忽略日志
                return AjaxObject.newError(e.getMessage()).setCallbackType("").toString();
            }
            LogUitls.putArgs(LogMessageObject.newWrite().setObjects(new Object[]{user.getUsername()}));
            return AjaxObject.newOk("修改密码成功！").toString();
        }

        return AjaxObject.newError("修改密码失败！").setCallbackType("").toString();
    }

    // 返回基本信息修改操作界面
    @RequiresUser
    @RequestMapping(value = "/updateBase", method = RequestMethod.GET)
    public String preUpdateBase(Map<String, Object> map) {
        Subject subject = org.apache.shiro.SecurityUtils.getSubject();
        User user = userService.getByUsername(subject.getPrincipal().toString());
        //map.put(SecurityConstants.LOGIN_USER, SecurityUtils.getLoginUser());
        map.put(SecurityConstants.LOGIN_USER, user);
        return UPDATE_BASE;
    }

    // 执行基本信息修改
    @Log(message = "{0}修改了详细信息。")
    @RequiresUser
    @RequestMapping(value = "/updateBase", method = RequestMethod.POST)
    public
    @ResponseBody
    String updateBase(User user, ServletRequest request) {
        //	User loginUser = SecurityUtils.getLoginUser();
        Subject subject = org.apache.shiro.SecurityUtils.getSubject();
        User loginUser = userService.getByUsername(subject.getPrincipal().toString());
        loginUser.setPhone(user.getPhone());
        loginUser.setEmail(user.getEmail());

        userService.saveOrUpdate(loginUser);

        LogUitls.putArgs(LogMessageObject.newWrite().setObjects(new Object[]{user.getUsername()}));
        return AjaxObject.newOk("修改详细信息成功！").toString();
    }
}
